import Vue from 'vue'
import { getToken } from '@/utils/session.js'

const BASE_URL = Vue.prototype.$url;
// 封装请求方法
const request = (obj) => {
	obj.url = obj.url || ''; // 请求路径
	obj.method = obj.method || 'GET'; //请求方式
	obj.data = obj.data || {}; //请求携带的数据
	obj.header = obj.header || 'application/json'; //请求头信息 content-type
	obj.loading = obj.loading === false ? false : true; //是否显示请求加载中
	obj.responseType = obj.responseType || 'text'
	

	//返回Promise对象
	return new Promise((resolve, reject) => {
		if (obj.loading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			});
		}

		uni.request({
			// url: BASE_URL + obj.url,
			// method: obj.method,
			// data: obj.data,
			...obj,
			url: BASE_URL + obj.url,
			header: {
				'Content-Type': obj.header,
				'TOKEN':getToken()
			},
			success: res => {
				obj.loading && uni.hideLoading();
				resolve(res);
			},
			fail: err => {
				obj.loading && uni.hideLoading();
				reject(err);
			},
			complete: (e) => {
				let { msg, code } = e.data;
				if (code == '401') {
					uni.$u.toast(msg);
					uni.redirectTo({
						url: '/pages/login/login'
					});
				}
			}
		})
	});
}

export default request;